package com.hotcode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: huangzhigao
 * @Date: 2023/2/25 19:20
 */
public class leecode207 {
    int[] flags;

    public boolean canFinish(int numCourses, int[][] prerequisites) {
        List<List<Integer>> graph = new ArrayList<>();
        for (int i = 0; i < numCourses; i++) {
            graph.add(new ArrayList<>());
        }
        for (int i = 0; i < prerequisites.length; i++) {
            graph.get(prerequisites[i][1]).add(prerequisites[i][0]);
        }
        flags = new int[numCourses];
        for (int i = 0; i < numCourses; i++) {
            if (!dfs(graph, i)) {
                return false;
            }
        }

        return true;

    }

    private boolean dfs(List<List<Integer>> adjacency, int i) {
        if (flags[i] == 1) return false;
        if (flags[i] == -1) return true;
        flags[i] = 1;
        for (Integer j : adjacency.get(i)) {
            if (!dfs(adjacency, j)) return false;
        }
        flags[i] = -1;
        return true;
    }

}
